<template>
  <ua-markdown :source="mdvalue" />
  <view class="chat-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-container">
        <up-search
          v-model="searchText"
          placeholder="Search for messages or users"
          prefixIcon="search"
          shape="square"
          :border="false"
          :clearable="true"
          :showAction="false"
          bgColor="#E6E6E7"
        ></up-search>
      </view>

      <view class="add-menu-container">
        <view
          class="add-button"
          :class="{ 'is-active': showDropdown }"
          @tap="toggleDropdown"
        >
          <up-icon name="plus" color="#333" size="20"></up-icon>
        </view>
        <view name="dropdown">
          <view class="dropdown-menu" v-if="showDropdown">
            <view
              class="dropdown-item"
              v-for="(item, index) in menuItems"
              :key="index"
              @tap="handleMenuClick(item)"
            >
              <text class="item-icon">{{ item.icon }}</text>
              <text class="item-label">{{ item.label }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <scroll-view scroll-y class="chat-list" style="height: calc(100vh - 17vh)">
      <view
        v-for="(chat, index) in chatList"
        :key="index"
        class="chat-item-wrapper"
      >
        <movable-area class="movable-area">
          <movable-view
            class="movable-view"
            :animation="false"
            direction="horizontal"
            :out-of-bounds="false"
            :damping="50"
            :x="chat.x"
            @change="handleMovableChange($event, index)"
            @touchend="handleTouchend($event, index)"
          >
            <!-- 聊天项主体内容 -->
            <view
              class="chat-item"
              @tap="handleChatTap(chat)"
              :class="{ 'pinned-chat': chat.isPinned }"
            >
              <view class="avatar">
                <image :src="chat.avatar" mode="aspectFill"></image>
                <view v-if="chat.unread" class="unread-badge">{{
                  chat.unread
                }}</view>
              </view>
              <view class="content">
                <view class="header">
                  <text class="name">{{ chat.name }}</text>
                  <text class="time">{{ chat.time }}</text>
                </view>
                <view class="message">
                  <text class="text">{{ chat.lastMessage }}</text>
                  <view v-if="chat.isPinned" class="pin-icon">📌</view>
                </view>
              </view>
            </view>

            <!-- 右侧操作按钮 -->
            <view class="action-buttons">
              <view class="action-btn mute" @tap="handleMute(index)">
                <text class="icon">🔇</text>
                <text>设为已读</text>
              </view>
              <view class="action-btn delete" @tap="handleDelete(index)">
                <text class="icon">🗑️</text>
                <text>删除</text>
              </view>
              <view class="action-btn archive" @tap="handleEdit(index)">
                <text class="icon">📦</text>
                <text>编辑</text>
              </view>
            </view>
          </movable-view>
        </movable-area>
      </view>
    </scroll-view>

    <!-- 编辑对话模态框 -->
    <view class="edit-modal-overlay" v-if="showEditModal" @tap="closeEditModal">
      <view class="edit-modal-content" @tap.stop="">
        <view class="edit-modal-header">
          <text class="edit-modal-title">编辑对话</text>
          <view class="edit-modal-close" @tap="closeEditModal">
            <up-icon name="close" color="#333" size="20"></up-icon>
          </view>
        </view>

        <view class="edit-modal-body">
          <!-- 头像选择 -->
          <view class="avatar-section">
            <image
              :src="editingChat.avatar"
              mode="aspectFill"
              class="edit-avatar"
            ></image>
            <view class="avatar-edit-btn" @tap="chooseAvatar">
              <up-icon name="camera" color="#fff" size="20"></up-icon>
            </view>
          </view>

          <!-- 名称输入 -->
          <view class="input-section">
            <text class="input-label">名称</text>
            <input
              type="text"
              v-model="editingChat.name"
              class="edit-input"
              placeholder="输入对话名称"
            />
          </view>

          <!-- 置顶选项 -->
          <view class="toggle-section">
            <text class="toggle-label">置顶对话</text>
            <switch
              :checked="editingChat.isPinned"
              @change="togglePin"
              color="#2979ff"
            />
          </view>

          <!-- 静音选项 -->
          <!-- <view class="toggle-section">
            <text class="toggle-label">设为已读</text>
            <switch :checked="editingChat.isMuted" @change="toggleMute" color="#2979ff" />
          </view> -->
        </view>

        <view class="edit-modal-footer">
          <button class="cancel-btn" @tap="closeEditModal">取消</button>
          <button class="save-btn" @tap="saveChanges">保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { encodeParams } from '@/utils/routerHelper.js';
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useChatMenu } from "@/stores/chatMenu.js";
const chatStore = useChatMenu();
const searchText = ref("");
const showDropdown = ref(false);
const value1 = ref("");
// 跟踪当前打开的滑动菜单项的索引
const openSwipeIndex = ref(-1);
// const mdvalue = '### uniapp markdwon'
const testMove = ref(0);
// 编辑模态框状态
const showEditModal = ref(false);
const editingIndex = ref(-1);
const editingChat = reactive({
  id: 0,
  name: "",
  avatar: "",
  lastMessage: "",
  time: "",
  unread: 0,
  isPinned: false,
  isMuted: false,
  x: 0,
});

// 使用Pinia store中的聊天列表数据
const chatList = ref([]);

const menuItems = ref([
  {
    icon: "✏️",
    label: "创建新对话",
    action: "new-chat",
  },
  {
    icon: "🤖",
    label: "创建 AI 智能体",
    action: "create-ai",
  },
]);

watch(openSwipeIndex, (newValue, oldValue) => {
  // console.log("openSwipeIndex changed:", newValue, oldValue)
  if (newValue !== oldValue && oldValue !== -1) {
    chatList.value[oldValue].x = 0;
    chatList.value = [...chatList.value];
    chatStore.changeChatMenu(chatList.value);
  }
});
/**
 * 处理滑动变化
 * @param {Object} e - 事件对象，包含详细信息
 * @param {number} index - 聊天列表中的索引
 */
const handleMovableChange = (e, index) => {
  // 如果有其他项已经打开，且不是当前项，则不允许滑动
  // if (openSwipeIndex.value !== -1 && openSwipeIndex.value !== index) {
  //   chatList.value[index].x = 0;
  //   return;
  // }

  const { x } = e.detail;
  // 更新聊天列表中对应项的x坐标
  // testMove.value = x;
  openSwipeIndex.value = index;
  chatList.value[index].x = x;
  chatList.value = [...chatList.value];
  chatStore.changeChatMenu(chatList.value);
  // console.log("move", chatList.value[index].x, index, testMove.value)

  // 不需要在这里同步到store，因为滑动过程中频繁更新会影响性能
  // 在handleTouchend中统一更新
};

// 处理滑动结束
const handleTouchend = (e, index) => {
  // console.log('x', x)
  // 同步更新到Pinia store
  // chatStore.changeChatMenu(chatList.value);
};

// 处理操作按钮点击
const handleMute = (index) => {
  // 切换静音状态
  // chatList.value[index].isMuted = !chatList.value[index].isMuted;
  chatList.value[index].unread = 0;
  uni.showToast({
    // title: chatList.value[index].isMuted ? "已静音" : "已取消静音",
    title: "已清空未读消息",
    icon: "none",
  });
  chatList.value[index].x = 0;
  // 同步更新到Pinia store
  chatStore.changeChatMenu(chatList.value);
};

// 打开编辑模态框
const handleEdit = (index) => {
  editingIndex.value = index;
  // 复制当前聊天项的数据到编辑对象
  Object.assign(editingChat, chatList.value[index]);
  // 显示模态框
  showEditModal.value = true;
  // 关闭滑动菜单
  chatList.value[index].x = 0;
};

// 关闭编辑模态框
const closeEditModal = () => {
  showEditModal.value = false;
  editingIndex.value = -1;
};

// 保存编辑更改
const saveChanges = () => {
  // console.log("saveChangesIndex", index)
  if (editingIndex.value !== -1) {
    // 记录之前的置顶状态
    const wasPinned = chatList.value[editingIndex.value].isPinned;

    // 更新聊天列表中的数据
    console.log("saveChanges", chatList.value[editingIndex.value], editingChat);
    editingChat.x = 0;
    Object.assign(chatList.value[editingIndex.value], editingChat);

    // 如果置顶状态发生了变化，重新排序聊天列表
    if (wasPinned !== editingChat.isPinned) {
      // 从列表中移除当前项
      const currentChat = chatList.value.splice(editingIndex.value, 1)[0];

      if (currentChat.isPinned) {
        // 如果是置顶，添加到列表开头
        chatList.value.unshift(currentChat);
      } else {
        // 如果取消置顶，找到最后一个置顶项的位置
        const lastPinnedIndex = chatList.value.findLastIndex(
          (chat) => chat.isPinned
        );
        // 将当前项插入到最后一个置顶项之后
        chatList.value.splice(lastPinnedIndex + 1, 0, currentChat);
      }
    }

    // 同步更新到Pinia store
    chatStore.changeChatMenu(chatList.value);
    // 显示成功提示
    uni.showToast({
      title: "保存成功",
      icon: "success",
    });
    // 关闭模态框
    closeEditModal();
  }
};

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      editingChat.avatar = res.tempFilePaths[0];
    },
  });
};

// 切换置顶状态
const togglePin = (e) => {
  editingChat.isPinned = e.detail.value;
};

// 切换静音状态
// const toggleMute = (e) => {
//   editingChat.isMuted = e.detail.value;
//   // 如果取消静音，将未读消息数设为0
//   if (!e.detail.value && editingChat.unread > 0) {
//     editingChat.unread = 0;
//     uni.showToast({
//       title: "已设为已读",
//       icon: "success"
//     });
//   }
// };

const handleDelete = (index) => {
  uni.showModal({
    title: "确认删除",
    content: "是否确认删除此聊天？",
    success: (res) => {
      if (res.confirm) {
        chatList.value.splice(index, 1);
        // 同步更新到Pinia store
        chatStore.changeChatMenu(chatList.value);
        uni.showToast({
          title: "已删除",
          icon: "success",
        });
      } else {
        // 如果取消删除，重置滑动位置
        chatList.value[index].x = 0;
      }
    },
  });
};

const handleArchive = (index) => {
  uni.showToast({
    title: "已存档",
    icon: "none",
  });
  chatList[index].x = 0;
};

// 处理聊天项点击
const handleChatTap = (chat) => {
  console.log("chat", chat);
  uni.navigateTo({
    url: `/pages/chatDetail/chatDetail?data=${encodeParams(chat)}`,
  });
};

// 处理新建聊天
const handleNewChat = () => {
  uni.navigateTo({
    url: "/pages/testAPi/testAPi",
  });
};

const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value;
};

// 点击其他区域关闭下拉菜单
const closeDropdown = () => {
  showDropdown.value = false;
};

// 整个聊天列表的右滑恢复
const handleSwipe = () => {
  // 读取pinia的内容并将所有列表项的x属性设置为0
  for (let i = 0; i < chatList.value.length; i++) {
    chatList.value[i].x = 0;
  }
};
// 处理菜单项点击
const handleMenuClick = (item) => {
  // handleSwipe();
  switch (item.action) {
    case "new-chat":
      createNewChat();
      closeDropdown();
      break;
    case "create-ai":
      uni.navigateTo({
        url: "/pages/addAgent/addAgent",
      });
      closeDropdown();
      break;
    // ... 处理其他选项
  }
  closeDropdown();
};

// 创建新聊天
const createNewChat = () => {
  // 生成唯一ID (简单实现，实际项目中可能需要更复杂的ID生成逻辑)
  const newId = Date.now();

  // 创建新的聊天对象
  const newChat = {
    id: newId,
    name: "新对话",
    avatar: "/static/img/chat/testUserA.jpg", // 默认头像
    lastMessage: "开始新的对话...",
    time: formatTime(new Date()),
    unread: 0,
    isPinned: false,
    isMuted: false,
    x: 0,
  };
  console.log(newChat, formatTime(new Date()), newChat.time);
  // 将新聊天添加到列表开头
  chatList.value.unshift(newChat);
  // 同步更新到Pinia store
  chatStore.changeChatMenu(chatList.value);
  // 导航到聊天详情页
  uni.navigateTo({
    url: `/pages/chatDetail/chatDetail?id=${newChat.id}&name=${newChat.name}&avatar=${newChat.avatar}&isNew=true`,
  });
};
// 格式化时间的辅助函数
const formatTime = (date) => {
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${month}/${day} ${hours}:${minutes}`;
};

// 关闭所有打开的滑动菜单
const closeAllSwipeItems = () => {
  if (openSwipeIndex.value !== -1) {
    chatList.value[openSwipeIndex.value].x = 0;
    openSwipeIndex.value = -1;
  }
};

// 添加点击外部关闭下拉菜单的逻辑
onMounted(() => {
  // 从Pinia store初始化聊天列表数据
  chatList.value = [...chatStore.chatMenu];

  // #ifdef H5
  // 关闭菜单 (仅在H5环境下添加document事件监听)
  document.addEventListener("click", (e) => {
    const dropdown = document.querySelector(".add-menu-container");
    if (dropdown && !dropdown.contains(e.target)) {
      closeDropdown();
    }
  });
  // 添加点击事件监听器，用于关闭滑动菜单
  document.addEventListener("click", (e) => {
    // 检查点击的元素是否在滑动菜单或其操作按钮内
    const isClickInSwipeMenu = e.target.closest(".movable-view") !== null;
    if (!isClickInSwipeMenu) {
      closeAllSwipeItems();
    }
  });
  // #endif

  // #ifdef APP-PLUS
  // 监听新意图事件
  // plus.globalEvent.addEventListener('click', function () { });
  // #endif
});

// 使用 onShow 生命周期
onShow(() => {
  // console.log('Page show', chatStore.chatMenu);
  // 每次页面显示时从Pinia store获取最新数据
  chatList.value = [...chatStore.chatMenu];

  // 确保所有滑动菜单都是关闭状态
  chatList.value.forEach((chat) => {
    chat.x = 0;
  });
  openSwipeIndex.value = -1;
  // 对聊天列表进行排序，确保置顶的对话显示在最前面
  chatList.value.sort((a, b) => {
    // 如果a置顶而b没有置顶，a排在前面
    if (a.isPinned && !b.isPinned) return -1;
    // 如果b置顶而a没有置顶，b排在前面
    if (!a.isPinned && b.isPinned) return 1;
    // 如果置顶状态相同，保持原有顺序
    return 0;
  });
  // 同步排序后的列表回到store
  chatStore.changeChatMenu(chatList.value);
  // 关闭所有打开的滑动菜单
  closeAllSwipeItems();
});
</script>

<style lang="scss" scoped>
// 文本省略混入
@mixin text-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.chat-container {
  height: 90vh;
  background-color: #fff;
  position: relative;
  display: flex;
  flex-direction: column;

  .search-bar {
    padding: 20rpx 30rpx;
    background-color: #f8f8f8;
    display: flex;
    align-items: center;
    gap: 20rpx;

    .search-container {
      flex: 1;
    }

    .add-menu-container {
      position: relative;

      .add-button {
        width: 72rpx;
        height: 72rpx;
        background-color: #e6e6e7;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;

        // 添加点击效果
        &:active {
          background-color: darken(#e6e6e7, 5%);
          transform: scale(0.95);
        }

        .add-icon {
          font-size: 40rpx;
          color: #333;
          transition: all 0.3s ease;
        }

        // 激活状态样式
        &.is-active {
          background-color: darken(#e6e6e7, 5%);

          .add-icon {
            transform: rotate(45deg);
          }
        }
      }

      .dropdown-menu {
        position: absolute;
        top: 100%;
        right: 0;
        width: 320rpx;
        background: #fff;
        border-radius: 16rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
        z-index: 100;
        margin-top: 10rpx;

        .dropdown-item {
          display: flex;
          align-items: center;
          padding: 24rpx 30rpx;

          &:active {
            background-color: #f5f5f5;
          }

          .item-icon {
            margin-right: 20rpx;
            font-size: 36rpx;
          }

          .item-label {
            font-size: 28rpx;
            color: #333;
          }
        }
      }
    }
  }

  .chat-list {
    height: calc(100vh - 112rpx);

    .chat-item-wrapper {
      width: 100%;

      .movable-area {
        width: 100%;
        height: 140rpx;

        .movable-view {
          width: calc(100% + 420rpx);
          height: 100%;
          display: flex;

          .chat-item {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            padding: 20rpx 30rpx;
            background-color: #fff;
            transition: background-color 0.3s ease;

            // 置顶聊天项的样式
            &.pinned-chat {
              background-color: #f0f7ff;
              border-left: 6rpx solid #2979ff;
            }

            .avatar {
              position: relative;
              margin-right: 20rpx;

              image {
                width: 100rpx;
                height: 100rpx;
                border-radius: 50%;
              }

              .unread-badge {
                position: absolute;
                right: -6rpx;
                top: -6rpx;
                background-color: #2979ff;
                color: #fff;
                font-size: 24rpx;
                padding: 4rpx 12rpx;
                border-radius: 20rpx;
                min-width: 36rpx;
                text-align: center;
              }
            }

            .content {
              flex: 1;

              .header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 8rpx;

                .name {
                  font-size: 32rpx;
                  font-weight: 500;
                  color: #333;
                }

                .time {
                  font-size: 24rpx;
                  color: #999;
                }
              }

              .message {
                display: flex;
                align-items: center;

                .text {
                  font-size: 28rpx;
                  color: #666;
                  flex: 1;
                  @include text-ellipsis;
                  display: inline-block;
                  width: 200rpx;
                }

                .pin-icon {
                  margin-left: 10rpx;
                  font-size: 24rpx;
                }
              }
            }
          }

          .action-buttons {
            display: flex;
            margin-left: auto;

            .action-btn {
              width: 140rpx;
              height: 140rpx;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              font-size: 24rpx;
              color: #fff;

              .icon {
                font-size: 48rpx;
                margin-bottom: 12rpx;
              }

              &.mute {
                background-color: #ff9800;
              }

              &.delete {
                background-color: #ff5252;
              }

              &.archive {
                background-color: #4caf50;
              }

              &:active {
                opacity: 0.8;
              }
            }
          }
        }
      }
    }
  }

  .fab-button {
    position: fixed;
    right: 40rpx;
    bottom: 40rpx;
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    background-color: #2979ff;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 12rpx rgba(41, 121, 255, 0.4);

    .icon {
      font-size: 40rpx;
      color: #fff;
    }
  }

  // 编辑模态框样式
  .edit-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: fadeIn 0.2s ease;

    .edit-modal-content {
      width: 80%;
      max-width: 600rpx;
      background-color: #fff;
      border-radius: 20rpx;
      overflow: hidden;
      box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
      animation: scaleIn 0.2s ease;

      .edit-modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 30rpx;
        border-bottom: 1rpx solid #eee;

        .edit-modal-title {
          font-size: 34rpx;
          font-weight: 500;
          color: #333;
        }

        .edit-modal-close {
          padding: 10rpx;

          &:active {
            opacity: 0.7;
          }
        }
      }

      .edit-modal-body {
        padding: 30rpx;

        .avatar-section {
          display: flex;
          justify-content: center;
          margin-bottom: 40rpx;
          position: relative;

          .edit-avatar {
            width: 160rpx;
            height: 160rpx;
            border-radius: 80rpx;
            border: 4rpx solid #f0f0f0;
          }

          .avatar-edit-btn {
            position: absolute;
            right: calc(50% - 80rpx);
            bottom: 0;
            width: 60rpx;
            height: 60rpx;
            border-radius: 30rpx;
            background-color: #2979ff;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);

            &:active {
              transform: scale(0.95);
            }
          }
        }

        .input-section {
          margin-bottom: 30rpx;

          .input-label {
            font-size: 28rpx;
            color: #666;
            margin-bottom: 10rpx;
            display: block;
          }

          .edit-input {
            width: 100%;
            height: 80rpx;
            border: 1rpx solid #ddd;
            border-radius: 8rpx;
            padding: 0 20rpx;
            font-size: 30rpx;
            color: #333;
            background-color: #f9f9f9;
          }
        }

        .toggle-section {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 30rpx;

          .toggle-label {
            font-size: 28rpx;
            color: #333;
          }
        }
      }

      .edit-modal-footer {
        display: flex;
        border-top: 1rpx solid #eee;

        button {
          flex: 1;
          height: 90rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 30rpx;
          border: none;
          background: none;

          &.cancel-btn {
            color: #666;
            border-right: 1rpx solid #eee;

            &:active {
              background-color: #f5f5f5;
            }
          }

          &.save-btn {
            color: #2979ff;
            font-weight: 500;

            &:active {
              background-color: rgba(41, 121, 255, 0.05);
            }
          }
        }
      }
    }
  }
}

// 添加过渡动画样式
.dropdown-enter-active,
.dropdown-leave-active {
  transition: all 0.3s ease;
  transform-origin: top right;
}

.dropdown-enter-from,
.dropdown-leave-to {
  opacity: 0;
  transform: scale(0.95);
}

.dropdown-enter-to,
.dropdown-leave-from {
  opacity: 1;
  transform: scale(1);
}

// 模态框动画
@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes scaleIn {
  from {
    transform: scale(0.9);
  }

  to {
    transform: scale(1);
  }
}
</style>
